﻿using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace SimpleLiteForm.Storage
{
    /// <summary>
    /// Helper class for file access.
    /// </summary>
    public static class IOHelper
    {
        /// <summary>
        /// Saves an image to the screenshots folder.
        /// </summary>
        /// <param name="image">The image to save.</param>
        /// <returns>The path to the saved image or null if an error occured.</returns>
        public static string SaveImage(Bitmap image)
        {
            var now = DateTime.Now;
            string filename = string.Format("screenshot-{0:000}{1:00}{2:00}-{3:00}{4:00}{5:00}.jpeg",
                now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
            string directory = "screenshots";
            string fullpath = string.Format("{0}/{1}", directory, filename);

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            if (File.Exists(fullpath))
                return null;

            using (var fs = new FileStream(fullpath, FileMode.Create))
            {
                image.Save(fs, ImageFormat.Jpeg);
            }
            
            return fullpath;
        }

        /// <summary>
        /// Saves the screen content to the screenshots folder.
        /// </summary>
        /// <param name="surface">The rendering surface to save.</param>
        /// <returns>The path to the saved image or null if an error occured.</returns>
        public static string SaveScreenshot(Surface s)
        {
            var now = DateTime.Now;
            string filename = string.Format("screenshot-{0:000}{1:00}{2:00}-{3:00}{4:00}{5:00}.jpeg",
                now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
            string directory = "screenshots";
            string fullpath = string.Format("{0}/{1}", directory, filename);

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            if (File.Exists(fullpath))
                return null;

            SurfaceLoader.Save(fullpath, ImageFileFormat.Jpg, (Surface)s);

            return fullpath;
        }

        /// <summary>
        /// Loads an image from a file.
        /// </summary>
        /// <param name="fullpath">The full path to the file.</param>
        /// <returns>Returns the bitmap image or null, if the file does not exists.</returns>
        public static Bitmap LoadImage(string fullpath)
        {
            if (File.Exists(fullpath))
                return new Bitmap(fullpath);
            else
                return null;
        }
    }
}
